package com.cmy.framework.room.test.manager

import android.annotation.SuppressLint
import android.content.Context
import com.cmy.framework.room.manager.BaseRoomManager
import com.cmy.framework.room.test.DBFactory
import com.cmy.framework.room.test.entity.TestEntity
import kotlinx.coroutines.*

/**
 * @name:
 *  DBManger
 * @package:
 *  com.cmy.test.mvp.dao
 * @date:
 *  2023/4/2611:22
 * @author
 *    cmy
 * @description
 *
 */
class DBManger(context: Context): BaseRoomManager(context) {

    companion object{

        @SuppressLint("StaticFieldLeak")
        @Volatile
        private var instance : DBManger? = null

        @Synchronized
        fun getInstance(context: Context):DBManger{
            if (instance == null){
                instance = DBManger(context)
            }
            return instance!!
        }
    }

    /**
     * 添加数据（此写法不推荐，容易阻塞线程）
     */
    fun insertTest(msg:String):Long = runBlocking(Dispatchers.IO) {
        val entity = TestEntity(msg = msg)
        return@runBlocking DBFactory.getInstance(mContext).getTestDao().insert(entity)
    }


    /**
     * 查询数据（推荐线程使用写法）
     */
    @OptIn(DelicateCoroutinesApi::class)
    fun findTestAll(): MutableList<TestEntity>? = runBlocking {
        val deferred = GlobalScope.async(Dispatchers.IO) {
            return@async DBFactory.getInstance(mContext).getTestDao().findAll()
        }
        return@runBlocking deferred.await()
    }
}